package com.rc.evcharger.common.base;


import com.rc.evcharger.common.annotation.Redis;
import com.rc.evcharger.common.annotation.RedisType;

import java.io.Serializable;
import java.lang.reflect.Field;

/**
 * Redis注解
 */
public class BaseRedis implements Serializable {
    Object value;

    public BaseRedis() {

    }

    public BaseRedis(String key, Object value) {
        try {
            Field[] fields = this.getClass().getDeclaredFields();
            String[] keys = key.split(":");
            int i = 1;
            for (Field field : fields) {
                Redis redis = field.getAnnotation(Redis.class);
                if (redis == null) {
                    continue;
                }
                if (redis.type().equals(RedisType.KEY)) {
                    field.set(this, keys[i]);
                    i++;

                } else if (redis.type().equals(RedisType.VALUE)) {
                    field.set(this, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getKey() {
        try {
            Field[] fields = this.getClass().getDeclaredFields();
            Redis table = this.getClass().getAnnotation(Redis.class);
            StringBuffer sb = new StringBuffer();
            sb.append(table.table()).append(":");
            for (Field field : fields) {
                field.setAccessible(true);
                Redis redis = field.getAnnotation(Redis.class);
                if (redis == null) {
                    continue;
                }
                if (redis.type().equals(RedisType.KEY)) {

                    if (null == field.get(this))
                        continue;
                    sb.append(field.get(this).toString());
                    sb.append(":");

                } else if (redis.type().equals(RedisType.VALUE)) {
                    this.value = field.get(this);
                }
            }
            String key = sb.toString();
            return key.substring(0, key.length() - 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Object getValue() {
        return value;
    }

    //public static void main(String[] args) {
    //    RedOccupy occupy = new RedOccupy("19 00 14 01", "1", 1000l, 1521645l);
    //    String key = occupy.getKey();
    //    System.out.println(key);
    //    Object value = occupy.getValue();
    //    System.out.println(value);
    //}
}
